/**  
 * Copyright © 2014公司名字. All rights reserved.
 *
 * @Title: ChuFangServiceImpl.java
 * @Prject: web
 * @Package: yang.service.impl
 * @Description: TODO
 * @author: Administrator  
 * @date: 2014年6月16日 下午9:37:21
 * @version: V1.0  
 */
package yang.service.impl;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import yang.dao.BaseDaoI;
import yang.model.ChufangInfo;
import yang.model.ChufangItmes;
import yang.model.HospitalDrug;
import yang.model.PatientInfo;
import yang.pageModel.ChuFang;
import yang.pageModel.ChuFangItem;
import yang.pageModel.DataGrid;
import yang.pageModel.Drug;
import yang.pageModel.Json;
import yang.service.ChuFangServiceI;

/**
 * @ClassName: ChuFangServiceImpl
 * @Description: TODO
 * @author: Administrator
 * @date: 2014年6月16日 下午9:37:21
 */
@Service("chufangService")
public class ChuFangServiceImpl implements ChuFangServiceI {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger
			.getLogger(ChuFangServiceImpl.class);

	private BaseDaoI<PatientInfo> patientDao;// 病人连接
	private BaseDaoI<ChufangInfo> chufangDao;// 处方
	private BaseDaoI<ChufangItmes> chufangItemsDao;// 处方明细
	private BaseDaoI<HospitalDrug> drugDao;// 药品
	/**
	 * 
	 * @Title: getChufangById
	 * @Description: 按ID返回处方
	 * @param chuFang
	 * @return
	 * @see yang.service.ChuFangServiceI#getChufangById(yang.pageModel.ChuFang)
	 */
	@Override
	public DataGrid getChufangById(ChuFang chuFang) {
		String hql = "from ChufangItmes c where c.chufangInfo.id=:id";
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("id", chuFang.getId());
		DataGrid grid = new DataGrid();
		List<ChufangItmes> itmes = chufangItemsDao.find(hql, params);
		// -----------------
		List<ChuFangItem> list = new ArrayList<ChuFangItem>();
		for (ChufangItmes chuFangItem : itmes) {
			ChuFangItem item = new ChuFangItem();
			BeanUtils.copyProperties(chuFangItem, item);
			item.setDrugName(chuFangItem.getHospitalDrug().getDrugName());
			list.add(item);
		}
		grid.setRows(list);
		grid.setTotal(Long.valueOf(list.size()));
		logger.info("完成");
		return grid;
	}

	/**
	 * @Title: saveChuFang
	 * @Description: 保存一个处方单
	 * @return
	 * @see yang.service.ChuFangServiceI#saveChuFang()
	 */
	@Override
	public Json saveChuFang(ChuFang chuFang) {
		Json json = new Json();
		String[] ids = chuFang.getIds().split(",");//三个都是前台传过来的字符串，所以在这里转化为数组
		String[] count = chuFang.getCounts().split(",");
		String[] yf = chuFang.getYf().split(",");
		try {
			//创建一个处方
			ChufangInfo info = new ChufangInfo();
			//为其赋值
			BeanUtils.copyProperties(chuFang, info);
			info.setPatientInfo(patientDao.get(PatientInfo.class,
					chuFang.getPatientId()));
			info.setId(UUID.randomUUID().toString());
			info.setCreatDate(new Timestamp(System.currentTimeMillis()));
			info.setTotalPrice(Double.valueOf(chuFang.getTatol()));
			//调用保存方法
			chufangDao.save(info);
			//为这个处方添加详细信息
			for (int i = 0; i < count.length; i++) {
				ChufangItmes chufangItmes = new ChufangItmes();
				chufangItmes.setChufangInfo(info);
				chufangItmes.setId(UUID.randomUUID().toString());
				HospitalDrug drug = drugDao.get(HospitalDrug.class, ids[i]);
				chufangItmes.setHospitalDrug(drug);
				int d = Integer.parseInt(count[i]);
				chufangItmes.setDrugYongfa(yf[i]);
				chufangItmes.setDrugShuliang(d);
				chufangItemsDao.save(chufangItmes);
			}
			//向前台输出
			json.setMsg("添加成功");
			json.setSuccess(true);
		} catch (BeansException e) {
			e.printStackTrace();
			json.setMsg("出现未知错误!");
		}

		return json;
	}

	/**
	 * @Title: findAllChuFang
	 * @Description: 查询所有的处方
	 * @return 数据表格
	 * @see yang.service.ChuFangServiceI#findAllChuFang()
	 */
	@Override
	public DataGrid findAllChuFang(ChuFang chuFang) {
		String hql = "from ChufangInfo c where 1=1";// 查询语句
		DataGrid dataGrid = new DataGrid();// 创建DATA
		Map<String, Object> params = new HashMap<String, Object>();// 查询条件
		hql = addWhere(chuFang, hql, params);// 为语句增加WHERE条件
		String totalHql = "select count(*) " + hql;// 查询总数的语句
		hql = addOrder(chuFang, hql);// 为查询语句增加ORDER条件
		List<ChufangInfo> list = chufangDao.find(hql, params,
				chuFang.getPage(), chuFang.getRows());// 进行查询
		List<ChuFang> list2 = new ArrayList<ChuFang>();// 建立模型
		changeModel(list, list2);// 为模型赋值
		dataGrid.setRows(list2);// 向前台输出了
		dataGrid.setTotal(chufangDao.count(totalHql, params));
		return dataGrid;
	}

	/**
	 * @Title: changeModel
	 * @Description: 为模型赋值
	 * @param list
	 * @param list2
	 * @return: void
	 */
	private void changeModel(List<ChufangInfo> list, List<ChuFang> list2) {
		if (list != null && list.size() > 0) {
			for (ChufangInfo chufangInfo : list) {
				//
				ChuFang chuFang = new ChuFang();
				//
				BeanUtils.copyProperties(chufangInfo, chuFang);
				chuFang.setPatientId(chufangInfo.getPatientInfo()
						.getPatientId());
				chuFang.setPname(chufangInfo.getPatientInfo().getPatientName());
				StringBuffer s = new StringBuffer("YY");
				for (int i = 0; i < 4 - chufangInfo.getPatientInfo()
						.getPatientTodayid().toString().length(); i++) {
					s.append("0");
				}
				s.append(chufangInfo.getPatientInfo().getPatientTodayid()
						.toString());
				chuFang.setTodayId(s.toString());
				list2.add(chuFang);
			}
		}
	}

	/**
	 * 
	 * @Title: addOrder
	 * @Description: 添加排序条件
	 * @param info
	 * @param hql
	 * @return: String
	 */
	private String addOrder(ChuFang info, String hql) {
		if (info.getSort() != null) {
			hql += " order by " + info.getSort() + " " + info.getOrder();
		}
		return hql;
	}

	/**
	 * 
	 * @Title: addWhere
	 * @Description: 添加查询条件
	 * @param info
	 * @param hql
	 *            查询语句
	 * @param params
	 *            参数
	 * @return: String
	 */
	private String addWhere(ChuFang info, String hql, Map<String, Object> params) {
		if (info.getInputText() != null
				&& !info.getInputText().trim().equals("")) {
			hql += " and c.patientInfo.patientName like :pname";
			params.put("pname", info.getInputText() + "%%");
		}
		if (info.getPatientType() != 0) {
			hql += " and c.patientInfo.patientType=:type";
			params.put("type", info.getPatientType());
		}
		return hql;
	}

	/**
	 * @Title: findByQ
	 * @Description: 查找药品信息
	 * @param drug
	 * @return
	 * @see yang.service.ChuFangServiceI#findByQ(yang.pageModel.Drug)
	 */
	@Override
	public DataGrid findByQ(String q) {
		String hql = "from HospitalDrug p";// 查询语句
		DataGrid dataGrid = new DataGrid();// 创建DATA
		Map<String, Object> params = new HashMap<String, Object>();// 查询条件
		if (q != null && !q.trim().equals("")) {
			hql += " where p.drugUnit like :drugUnit";
			params.put("drugUnit", q + "%%");
		}
		List<HospitalDrug> list = drugDao.find(hql, params);// 进行查询
		List<Drug> list2 = new ArrayList<Drug>();// 建立模型
		if (list != null && list.size() > 0) {
			for (HospitalDrug patientInfo : list) {
				Drug drug2 = new Drug();
				BeanUtils.copyProperties(patientInfo, drug2);
				list2.add(drug2);
			}
		}
		dataGrid.setRows(list2);// 向前台输出了
		return dataGrid;
	}
	//------ get set ---------
	public BaseDaoI<ChufangInfo> getChufangDao() {
		return chufangDao;
	}

	@Autowired
	public void setChufangDao(BaseDaoI<ChufangInfo> chufangDao) {
		this.chufangDao = chufangDao;
	}

	public BaseDaoI<ChufangItmes> getChufangItemsDao() {
		return chufangItemsDao;
	}

	@Autowired
	public void setChufangItemsDao(BaseDaoI<ChufangItmes> chufangItemsDao) {
		this.chufangItemsDao = chufangItemsDao;
	}

	public BaseDaoI<HospitalDrug> getDrugDao() {
		return drugDao;
	}

	@Autowired
	public void setDrugDao(BaseDaoI<HospitalDrug> drugDao) {
		this.drugDao = drugDao;
	}

	public BaseDaoI<PatientInfo> getPatientDao() {
		return patientDao;
	}

	@Autowired
	public void setPatientDao(BaseDaoI<PatientInfo> patientDao) {
		this.patientDao = patientDao;
	}

}
